'use client';
import { useCallback, useState } from 'react';

type Status = 'idle' | 'loading' | 'granted' | 'denied' | 'error' | 'unsupported';

interface GeolocationError {
  code: number;
  message: string;
}

export interface LocationCoords {
  latitude: number;
  longitude: number;
  accuracy?: number;
}

export function useGeolocation() {
  const [status, setStatus] = useState<Status>('idle');
  const [coords, setCoords] = useState<LocationCoords | null>(null);
  const [error, setError] = useState<GeolocationError | null>(null);

  const request = useCallback(() => {
    // 检查浏览器是否支持地理位置API
    if (!('geolocation' in navigator)) {
      setStatus('unsupported');
      setError({
        code: -1,
        message: '您的浏览器不支持地理位置功能',
      });
      return;
    }

    setStatus('loading');
    setError(null);

    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude, accuracy } = position.coords;
        setCoords({ latitude, longitude, accuracy });
        setStatus('granted');
        setError(null);
      },
      (err) => {
        setStatus('denied');

        // 根据错误码提供友好的错误信息
        let message = '获取位置信息失败';
        switch (err.code) {
          case err.PERMISSION_DENIED:
            message = '位置权限被拒绝，请在浏览器设置中允许位置访问';
            break;
          case err.POSITION_UNAVAILABLE:
            message = '位置信息不可用，请检查GPS或网络连接';
            break;
          case err.TIMEOUT:
            message = '获取位置信息超时，请重试';
            break;
          default:
            message = err.message || '未知的位置获取错误';
        }

        setError({
          code: err.code,
          message,
        });
      },
      {
        enableHighAccuracy: true, // 启用高精度定位
        timeout: 10000, // 10秒超时
        maximumAge: 300000, // 5分钟缓存
      },
    );
  }, []);

  // 重置状态
  const reset = useCallback(() => {
    setStatus('idle');
    setCoords(null);
    setError(null);
  }, []);

  // 检查是否有有效的坐标
  const hasValidCoords =
    coords &&
    typeof coords.latitude === 'number' &&
    typeof coords.longitude === 'number' &&
    !isNaN(coords.latitude) &&
    !isNaN(coords.longitude);

  return {
    status,
    coords,
    error,
    request,
    reset,
    hasValidCoords,
    isLoading: status === 'loading',
    isGranted: status === 'granted' && hasValidCoords,
    isDenied: status === 'denied',
    isUnsupported: status === 'unsupported',
  };
}
